package com.hsjk.szwj.module.pay.util;

import cn.hutool.extra.spring.SpringUtil;
import com.github.binarywang.wxpay.bean.request.BaseWxPayRequest;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.hsjk.szwj.framework.common.util.spring.SpringBeansUtil;
import com.hsjk.szwj.module.pay.dal.dataobject.config.ChannelRetMsg;
import com.hsjk.szwj.module.pay.dal.dataobject.config.MchAppConfigContext;
import com.hsjk.szwj.module.pay.dal.dataobject.config.WxServiceWrapper;
import com.hsjk.szwj.module.pay.dal.dataobject.config.WxpayIsvsubMchParams;
import com.hsjk.szwj.module.pay.service.ConfigContextQueryService;
import org.apache.commons.lang3.StringUtils;

/**
 * @author chenjiawei
 * @desc 【微信支付】支付通道工具包
 * @Date 2023/08/25 00:07
 **/
public class WxpayKit {

    /**
     * 放置 isv特殊信息
     **/
    public static void putApiIsvInfo(MchAppConfigContext mchAppConfigContext,
                                     BaseWxPayRequest req) {

        //不是特约商户， 无需放置此值
        if (!mchAppConfigContext.isIsvsubMch()) {
            return;
        }

        ConfigContextQueryService configContextQueryService
                = SpringUtil.getBean(ConfigContextQueryService.class);

        WxpayIsvsubMchParams isvsubMchParams =
                (WxpayIsvsubMchParams) configContextQueryService
                        .queryIsvsubMchParams(mchAppConfigContext.getMchId(),
                                mchAppConfigContext.getAppId(), mchAppConfigContext.getIfCodeId());


        req.setSubMchId(String.valueOf(isvsubMchParams.getSubMchId()));
        req.setSubAppId(String.valueOf(isvsubMchParams.getSubMchAppId()));
    }

    /**
     * 构造服务商 + 商户配置  wxPayConfig
     **/
    public static WxPayConfig getWxPayConfig(WxServiceWrapper wxServiceWrapper) {
        return wxServiceWrapper.getWxPayService().getConfig();
    }

    public static String appendErrCode(String code, String subCode) {
        //优先： subCode
        return StringUtils.defaultIfEmpty(subCode, code);
    }

    public static String appendErrMsg(String msg, String subMsg) {

        if (StringUtils.isNotEmpty(msg) && StringUtils.isNotEmpty(subMsg)) {
            return msg + "【" + subMsg + "】";
        }
        return StringUtils.defaultIfEmpty(subMsg, msg);
    }

    public static void commonSetErrInfo(ChannelRetMsg channelRetMsg, WxPayException wxPayException) {

        channelRetMsg.setChannelErrCode(appendErrCode(wxPayException.getReturnCode(), wxPayException.getErrCode()));
        channelRetMsg.setChannelErrMsg(appendErrMsg("OK".equalsIgnoreCase(wxPayException.getReturnMsg()) ? null : wxPayException.getReturnMsg(), wxPayException.getErrCodeDes()));

        // 如果仍然为空
        if (StringUtils.isEmpty(channelRetMsg.getChannelErrMsg())) {
            channelRetMsg.setChannelErrMsg(StringUtils.defaultIfEmpty(wxPayException.getCustomErrorMsg(), wxPayException.getMessage()));
        }

    }
}
